<template>
  <div class="chat-container">
    <!-- 训练 -->
    <div class="topImg">
      <img src="../../assets/aixl.png" alt="" style="width: 100%" />
    </div>
    <!-- 训练结束 -->

    <!-- <a-tabs defaultActiveKey="1" @change="callback">
      <a-tab-pane tab="AI聊天" key="1" >

      </a-tab-pane>
      <a-tab-pane tab="AI绘画" key="2" forceRender>

      </a-tab-pane>
      <a-tab-pane tab="AI训练" key="3" forceRender>

      </a-tab-pane>
    </a-tabs> -->
    <!-- 聊天内容 -->

  </div>
</template>
  
<script>
import { EventSourcePolyfill } from 'event-source-polyfill'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { mapActions, mapGetters, mapState } from 'vuex'
import TopNav from './component/TopNav.vue';
//   import { JeecgListMixin } from '@/mixins/JeecgListMixin'
export default {
  name: 'ChatModelTrain',
  mixins: [],
  components: {
    TopNav
  },
  data() {
    return {
      url: {
        list: '/sys/role/list',
      },
      listData: [],
      listData2: [
        { role: 'user', list: [{}] },
        { role: 'assistant', list: [{}] },
      ],
      imgShow: '',
      imgShowBool: true,
      imgLoading: false,
      timer: null,
      wen: '',
      messages: [],
      newMessage: '',
      newImage: '',
      oldScrollTop: 0,
      scrollFlag: true,
      Intervall: null,
      activeStep: '', // 默认选中的锚点的key值
      offsetTop: 0,
      serverHTML: '',
      ActiveKey: '1',
    }
  },
  render(h) {
    return h('div', {
      class: 'md',
      domProps: {
        innerHTML: this.text,
      },
    })
  },
  directives: {
    scroll: {
      inserted(el) {
        el.scrollIntoView()
      },
    },
  },
  computed: {
    isInputEmpty() {
      return this.newMessage.trim() === ''
    },
    isInputEmpty1() {
      return this.newImage.trim() === ''
    },
  },

  watch: {
    //监听路由地址的改变
    $route: {
      immediate: true,
      handler() {
        let path = this.$route.fullPath
        let Mode = path.substr(path.indexOf('Mode=') + 5).trim() + ''
        console.log('Mode', Mode)
        switch (Mode) {
          case '1':
            this.ActiveKey = Mode
            break
          case '2':
            this.ActiveKey = Mode
            break
          default:
            this.ActiveKey = Mode
        }
      },
    },
  },

  mounted() {
    //查询聊天记录
    // this.workplaceTeams('', 'query')

    // this.$nextTick(function () {
    //   const observer = new ResizeObserver((entries) => {
    //     for (let entry of entries) {
    //       // 获取标签的高度
    //       const height = entry.contentRect.height

    //       // 在这里可以对高度进行处理
    //       this.scrollToBottom()
    //       console.log('标签的高度:', height)
    //     }
    //   })
    //   // 监听组件根元素的变化
    //   observer.observe(this.$refs.myElement)
    // })
  },
  beforeDestroy() {
    //清除定时器
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    //选项卡下标
    callback(key) {
      console.log(key)
      this.imgShowBool = true
      this.imgLoading = false
      let obj = {
        content: '',
        n: 1,
        size: '512x512',
      }
      this.$http
        .post('/openai/api/image', obj)
        .then((res) => {
          console.log('res', res)
          this.listData2 = res.result
          // this.$refs.modalForm2.getListGroupBy(this.listData2,'role')
        })
        .catch((error) => {
          console.log('error', error)
          // 处理请求失败
        })
    },
    //滚动条保持最底部方法
    scrollToBottom() {
      this.$nextTick(() => {
        var container = this.$el.querySelector('.chat')
        container.scrollTop = container.scrollHeight
      })
    },
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '提示词模板'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd1: function () {
      this.$refs.modalForm1.add()
      this.$refs.modalForm1.title = '对话记录'
      this.$refs.modalForm1.disableSubmit = false
    },
    handleAdd2: function () {
      this.$refs.modalForm2.add()
      this.$refs.modalForm2.title = '历史图片生成'
      this.$refs.modalForm2.disableSubmit = true
    },
    modalFormOk(data) {
      console.log('data', data)
      this.newMessage = data.content
      this.sendMessage(data.content)
    },
    modalFormOk1(data) {
      console.log(data)
      this.activeStep = data.id
      const element = document.getElementById('item-' + data.id)
      const content = this.$refs.myElement
      console.log(element.offsetTop, content.offsetTop)
      if (element && content) {
        const scrollTop = element.offsetTop - content.offsetTop
        content.scrollTop = scrollTop
      }
    },
    modalFormOk2() {},
    //复制
    copyText(data) {
      const text = data // 要复制的文本内容
      const el = document.createElement('textarea')
      el.value = text
      document.body.appendChild(el)
      el.select()
      document.execCommand('copy')
      document.body.removeChild(el)
      this.$message.success('文本已复制')
    },

    //发出信息
    sendMessage() {
      if (this.newMessage.trim() !== '') {
        //我发出的
        this.messages.push({
          role: 'user',
          content: this.newMessage,
        })

        this.messages.push({
          role: 'assistant',
          content: '',
        })
        // this.output(this.newMessage)
        this.workplaceTeams(this.newMessage, 'submit')
        this.newMessage = ''
      }
    },
    //图片
    sendImage() {
      this.imgShowBool = true
      this.imgLoading = false
      if (this.newImage.trim() !== '') {
        this.imgLoading = true
        let obj = {
          content: this.newImage,
          n: 1,
          size: '512x512',
        }
        this.$http
          .post('/openai/api/image', obj)
          .then((res) => {
            console.log('res', res)
            this.imgShowBool = false
            this.imgLoading = false
            this.listData2 = res.result
            this.imgShow = res.result[res.result.length - 1].content
            this.$message.success('生成图片成功！')
          })
          .catch((error) => {
            console.log('error', error)
            // 处理请求失败
          })
        this.newImage = ''
      }
    },
    workplaceTeams(meg, type) {
      console.log('meg', meg)
      let obj = {
        content: meg,
      }
      this.$http
        .post('/openai/api/ask', obj)
        .then((res) => {
          console.log('res', res)
          if (res.success && type === 'submit') {
            //调用保持滚动条方法（这一步也可以在updated生命周期调用）
            let messages = res.result
            // this.$set(this.messages, this.messages.length - 1, {content:'',role:'assistant'})
            this.characters(messages[messages.length - 1].content)
          } else {
            this.messages = res.result
            this.listData = res.result
          }
        })
        .catch((error) => {
          console.log('error', error)
          // 处理请求失败
        })
    },
    //琢个字显示
    characters(meg) {
      this.data = meg
      this.wen = ''
      //声明一个变量，用来监听要分割的长度
      var wenLen = 0
      this.timer = setInterval(() => {
        //取到data.content的第wenLen位
        this.wen = this.data.substr(0, wenLen)

        //wenLen大于data.content的长度，停止计时器
        if (wenLen < this.data.length) {
          wenLen++
        } else {
          clearInterval(this.timer)
          // return
        }
        // console.log(' this.wen', this.wen)
        this.$set(this.messages[this.messages.length - 1], 'content', this.wen)
      }, 50)
    },
    output(meg) {
      let arr = [
        {
          content: meg,
          role: 'user',
        },
      ]
      let source = new EventSourcePolyfill('http://192.168.0.54:8080/jeecg-boot/openai/api/ask', {
        method: 'POST',
        headers: {
          'X-Access-Token': this.$ls.get(ACCESS_TOKEN),
          'Content-Type': 'application/json',
        },
        // mode: "cors",
        // cache: "no-cache",
        data: JSON.stringify(arr),
        onopen(response) {
          console.log('eventSource open : ', response)
        },
        onmessage(event) {
          console.log('eventSource msg1 :', event)
        },
        onerror(err) {
          console.log('eventSource error: ' + err)
        },
        onclose() {
          console.log('eventSource close')
        },
      })
      //   let innerHTML = ''
      source.onmessage = function (e) {
        console.log('e', e)
        if (e.data == '[done]') {
          source.close()
        } else {
          innerHTML += e.data
          document.getElementById('message').innerHTML = innerHTML
        }
      }
    },
  },
}
</script>
  
  <style lang="less" scoped >
.chatFunction {
  float: left;
  width: 100%;
  padding-top: 10px;
  position: relative;
}
.chat-atn {
  &.pop {
    color: #7a46fc;
    background: transparent;
    border-color: #7a46fc;
  }
  &.middle {
    height: 35px;
    padding: 0 23px;
    line-height: 35px;
    float: left;
    margin-right: 10px;
  }
}

.chat-messages {
  display: flex;
  align-items: center;
  margin: 12px 0 20px 0;
  float: left;
  width: 100%;
  .chat-input {
    flex: 1;
    border: none;
    outline: none;
    resize: none;
    border-radius: 8px;
    height: 60px;
    line-height: 20px;
    padding: 10px 20px;
    box-shadow: 0 5px 25px #193e7b14;
    margin-right: 10px;
  }
}

.chat-atn {
  border-radius: 4px;
  line-height: 1.5715;
  border: 1px solid transparent;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
  touch-action: manipulation;
  height: 32px;
  padding: 4px 15px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.25);
  background: #f5f5f5;
  border-color: #d9d9d9;
  text-shadow: none;
  box-shadow: none;
  display: flex;
  align-items: center;
  justify-content: center;
  &.disable {
    cursor: not-allowed;
  }
  &.active {
    background: #7a46fc;
    border-color: #7a46fc;
    color: white;
    cursor: pointer;
  }
  .iconfont {
    margin-right: 5px;
  }
}
.chat-atn:hover {
  opacity: 0.7;
}
.chat {
  height: 450px;
  overflow-y: auto;
  .classify.right {
    width: 100%;
    text-align: right;
    display: block;
    .chatBox {
      width: 100%;
      display: flex;
      flex-direction: row-reverse;
    }
    .message {
      float: right;
    }
    img {
      margin-left: 10px;
    }
    .message-text {
      text-align: left;
      &.active {
        // background: linear-gradient(to bottom,blue,red);
        animation-name: blink;
        animation-duration: 5s;
      }
      @keyframes blink {
        0% {
          opacity: 1;
          color: red;
        }
        50% {
          opacity: 0.8;
          color: red;
        }
        70% {
          opacity: 0.6;
        }
        100% {
          opacity: 1;
        }
      }
    }
    .iconList {
      margin-right: 10px;
    }
  }
  .classify.left {
    .message {
      float: left;
    }
    img {
      margin-right: 10px;
    }
    .iconList {
      margin-left: 10px;
    }
  }
  .classify {
    margin-bottom: 20px;
    float: left;
    width: 100%;
    .chatBox {
      display: flex;
      align-items: center;
      .chat-header {
        float: left;
        img {
          width: 40px;
          height: 40px;
        }
      }
      .messages {
        max-width: 80%;
        float: left;
        .message {
        }
      }
    }
  }
  .message-text {
    background-color: #f7f7f7;
    padding: 10px 20px;
    border-radius: 8px;
    color: #24292f;
    font-size: 15px;
  }
}
.iconList {
  .iconDt {
    background: #f7f7f7;
    border-radius: 20px;
    height: 30px;
    width: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.ant-btn {
  border: unset;
  border-color: unset;
}
.loading {
  width: 22px;
  height: 22px;
  border: 2px solid #1890ff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: rotate 0.75s linear infinite;
  float: right;
  margin-left: 4px;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

// AI绘画
.middle_con {
  padding: 20px 20px 0 20px;
  .middle_top {
    width: 100%;
    height: calc(100% - 60px);
    display: flex;
    align-items: center;
    justify-content: center;
    .main_image {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 20px;
      .image_container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        img {
          width: 200px;
          height: 200px;
          -o-object-fit: cover;
          object-fit: cover;
        }
        .title {
          color: #333;
          font-size: 16px;
          font-weight: 600;
        }
        .desc {
          color: #999;
          margin-top: 10px;
        }
      }
    }
  }
}
.main_sc {
  width: 320px;
  height: 320px;
  img {
    width: 100%;
    border: none;
  }
}

.main_sc .message-text {
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
}
.fixBoom {
  position: absolute;
  bottom: 7px;
  left: 50%;
  width: 100px;
  color: black;
  background: transparent;
  border: 1px solid black;
  text-align: center;
  border-radius: 4px;
  cursor: pointer;
}
.fixBoom:hover {
  opacity: 0.7;
}
.topImg{
  padding-top: 12px;
    float: left;
    background: #f6f6f6;
}
</style>
  